package com.niubi.yygh.orders.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.niubi.yygh.client.hosp.HospitalFeignClient;
import com.niubi.yygh.client.user.PatientFeignClient;
import com.niubi.yygh.common.exception.YyghException;
import com.niubi.yygh.enums.OrderStatusEnum;
import com.niubi.yygh.model.order.OrderInfo;
import com.niubi.yygh.model.user.Patient;
import com.niubi.yygh.orders.mapper.OrderInfoMapper;
import com.niubi.yygh.orders.service.OrderInfoService;

import com.niubi.yygh.orders.service.WeixinService;
import com.niubi.yygh.rabbit.RabbitService;
import com.niubi.yygh.rabbit.constant.MqConst;
import com.niubi.yygh.vo.hosp.ScheduleOrderVo;
import com.niubi.yygh.vo.msm.MsmVo;
import com.niubi.yygh.vo.order.OrderCountQueryVo;
import com.niubi.yygh.vo.order.OrderCountVo;
import com.niubi.yygh.vo.order.OrderMqVo;
import com.niubi.yygh.vo.order.OrderQueryVo;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import util.BeanUtils;
import util.HttpRequestHelper;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author 牛俊杰
 * @since 2022-03-29
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {

  @Lazy
  @Autowired
  WeixinService weixinService;
  @Autowired
  PatientFeignClient patientFeignClient;
  @Autowired
  HospitalFeignClient hospitalFeignClient;
  @Autowired
  RabbitService rabbitService;


  @Override
  public Long saveOrder(String scheduleId, Long patientId) {
    //根据patientId获取就诊人信息
    Patient patient = patientFeignClient.getPatient(patientId);
    //根据scheduleId获取排版数据
    ScheduleOrderVo scheduleOrderVo = hospitalFeignClient.getScheduleOrderVo(scheduleId);
    //调用医院系统接口进行挂号
        //封装调用医院系统需要数据
    Map<String, Object> paramMap = new HashMap<>();
    paramMap.put("hoscode",scheduleOrderVo.getHoscode());
    paramMap.put("depcode",scheduleOrderVo.getDepcode());
    paramMap.put("hosScheduleId",scheduleOrderVo.getHosScheduleId());
    paramMap.put("reserveDate",new DateTime(scheduleOrderVo.getReserveDate()).toString("yyyy-MM-dd"));
    paramMap.put("reserveTime", scheduleOrderVo.getReserveTime());
    paramMap.put("amount",scheduleOrderVo.getAmount()); //挂号费用
    paramMap.put("name", patient.getName());
    paramMap.put("certificatesType",patient.getCertificatesType());
    paramMap.put("certificatesNo", patient.getCertificatesNo());
    paramMap.put("sex",patient.getSex());
    paramMap.put("birthdate", patient.getBirthdate());
    paramMap.put("phone",patient.getPhone());
    paramMap.put("isMarry", patient.getIsMarry());
    paramMap.put("provinceCode",patient.getProvinceCode());
    paramMap.put("cityCode", patient.getCityCode());
    paramMap.put("districtCode",patient.getDistrictCode());
    paramMap.put("address",patient.getAddress());
    //联系人
    paramMap.put("contactsName",patient.getContactsName());
    paramMap.put("contactsCertificatesType", patient.getContactsCertificatesType());
    paramMap.put("contactsCertificatesNo",patient.getContactsCertificatesNo());
    paramMap.put("contactsPhone",patient.getContactsPhone());
    paramMap.put("timestamp", HttpRequestHelper.getTimestamp());
    //String sign = HttpRequestHelper.getSign(paramMap, signInfoVo.getSignKey());
    paramMap.put("sign", "");
    //医院系统接口返回成功,获取医院系统返回数据
    JSONObject result = HttpRequestHelper.sendRequest(paramMap, "http://localhost:9998/order/submitOrder");
    if (result.getInteger("code")==200){
      JSONObject jsonObject = result.getJSONObject("data");
      //预约记录唯一标识（医院预约记录主键）
      String hosRecordId = jsonObject.getString("hosRecordId");
      //预约序号
      Integer number = jsonObject.getInteger("number");
      //取号时间
      String fetchTime = jsonObject.getString("fetchTime");
      //取号地址
      String fetchAddress = jsonObject.getString("fetchAddress");
      //数据添加订单表
      OrderInfo orderInfo = new OrderInfo();
      BeanUtils.copyProperties(scheduleOrderVo,orderInfo);
      //设置其他值
      //订单号
      String outTradeNo = System.currentTimeMillis() + ""+ new Random().nextInt(100);
      orderInfo.setOutTradeNo(outTradeNo);
      orderInfo.setScheduleId(scheduleId);
      orderInfo.setUserId(patient.getUserId());
      orderInfo.setPatientId(patientId);
      orderInfo.setPatientName(patient.getName());
      orderInfo.setPatientPhone(patient.getPhone());
      orderInfo.setOrderStatus(OrderStatusEnum.UNPAID.getStatus());

      //设置添加数据--医院接口返回数据
      orderInfo.setHosRecordId(hosRecordId);
      orderInfo.setNumber(number);
      orderInfo.setFetchTime(fetchTime);
      orderInfo.setFetchAddress(fetchAddress);
      baseMapper.insert(orderInfo);

      //生成单成功之后,给挂号成功的就诊人发送短信通知
      ///排班可预约数
      Integer reservedNumber = jsonObject.getInteger("reservedNumber");
      //排班剩余预约数
      Integer availableNumber = jsonObject.getInteger("availableNumber");
      OrderMqVo orderMqVo = new OrderMqVo();
      orderMqVo.setScheduleId(scheduleId);
      orderMqVo.setAvailableNumber(availableNumber);
      orderMqVo.setReservedNumber(reservedNumber);
      MsmVo msmVo = new MsmVo();
      msmVo.setPhone(orderInfo.getPatientPhone());
      orderMqVo.setMsmVo(msmVo);
      //嘎松mq短信
      rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER,MqConst.ROUTING_ORDER,orderMqVo);
      //返回订单号
      return orderInfo.getId();
    }else {
      throw new YyghException(20001,"挂号失败");
    }
  }

  @Override
  public IPage<OrderInfo> selectPage(Page<OrderInfo> pageParam, OrderQueryVo orderQueryVo) {
    //获取条件
    //orderQueryVo获取条件值
    String name = orderQueryVo.getKeyword(); //医院名称
    Long patientId = orderQueryVo.getPatientId(); //就诊人名称
    String orderStatus = orderQueryVo.getOrderStatus(); //订单状态
    String reserveDate = orderQueryVo.getReserveDate();//安排时间
    String createTimeBegin = orderQueryVo.getCreateTimeBegin();
    String createTimeEnd = orderQueryVo.getCreateTimeEnd();
    //判断条件是否为空,封装
    QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
    if (!StringUtils.isEmpty(name)){
      wrapper.like("hosname",name);
    }
    if(!StringUtils.isEmpty(patientId)) {
      wrapper.eq("patient_id",patientId);
    }
    if(!StringUtils.isEmpty(orderStatus)) {
      wrapper.eq("order_status",orderStatus);
    }
    if(!StringUtils.isEmpty(reserveDate)) {
      wrapper.eq("reserve_date",reserveDate);
    }
    if(!StringUtils.isEmpty(createTimeBegin)) {
      wrapper.ge("create_time",createTimeBegin);
    }
    if(!StringUtils.isEmpty(createTimeEnd)) {
      wrapper.le("create_time",createTimeEnd);
    }
    Long userId = orderQueryVo.getUserId();
    wrapper.eq("user_id",userId);
    //调用方法得到结果
    IPage<OrderInfo> pages = baseMapper.selectPage(pageParam, wrapper);
    pages.getRecords().stream().forEach(item->{
      this.packageOrder(item);
    });
    return pages;
  }

  @Override
  public OrderInfo getOrderInfo(Long orderId) {
    OrderInfo orderInfo = baseMapper.selectById(orderId);
    return this.packageOrder(orderInfo);
  }

  @Override
  public Boolean cancelOrder(Long orderId) {
    //orderId查询数据
    OrderInfo orderInfo = this.getOrderInfo(orderId);
    //1 判断当前日期时间 是否 过了可以退号日期时间
    Date date = orderInfo.getQuitTime();
    DateTime quitTime = new DateTime(date);
//        if(quitTime.isBeforeNow()) {
//            throw new YyghException(20001,"不能退号，过了退号时间");
//        }

    //2 调用医院接口是否可以退号
    //2.1 封装医院接口需要参数
    Map<String, Object> reqMap = new HashMap<>();
    reqMap.put("hoscode",orderInfo.getHoscode());
    reqMap.put("hosRecordId",orderInfo.getHosRecordId());
    reqMap.put("timestamp", HttpRequestHelper.getTimestamp());
    reqMap.put("sign", "");

    //2.2 发送请求调用 httpclient
    JSONObject result =
            HttpRequestHelper.sendRequest(reqMap,"http://localhost:9998/order/updateCancelStatus");
    //3 根据医院接口返回状态判断
    if(result.getInteger("code") != 200) { //失败
      throw new YyghException(20001,"退号失败");
    } else { //返回成功
      //4 如果医院接口返回成功，微信退款
      boolean isRefund = weixinService.refund(orderId);
      if(!isRefund) {
        throw new YyghException(20001,"微信退款失败");
      }

      //5 修改订单状态 已经取消 -1
      orderInfo.setOrderStatus(OrderStatusEnum.CANCLE.getStatus());
      baseMapper.updateById(orderInfo);

      //6 整合mq消息发送，号数量更新
      //封装到OrderMqVo
      OrderMqVo orderMqVo = new OrderMqVo();
      //排班id
      orderMqVo.setScheduleId(orderInfo.getScheduleId());
      //封装短信
      MsmVo msmVo = new MsmVo();
      msmVo.setPhone(orderInfo.getPatientPhone());
      orderMqVo.setMsmVo(msmVo);
      //发送mq消息
      rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER,
              MqConst.ROUTING_ORDER,orderMqVo);
    }
    return true;
  }

  @Override
  public void patientTips(String dateString) {
    QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
    //查询就诊日期
    queryWrapper.eq("reserve_date",dateString);
    //查询没有取消的订单
    queryWrapper.ne("order_status",OrderStatusEnum.CANCLE.getStatus());
    List<OrderInfo> orderInfoList = baseMapper.selectList(queryWrapper);
    for(OrderInfo orderInfo : orderInfoList) {
      //短信提示
      MsmVo msmVo = new MsmVo();
      msmVo.setPhone(orderInfo.getPatientPhone());
      //发送mq发送短信
      rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_MSM, MqConst.ROUTING_MSM_ITEM, msmVo);
    }
  }

  @Override
  public Map<String, Object> getCountMap(OrderCountQueryVo orderCountQueryVo) {
    Map<String, Object> map = new HashMap<>();

    List<OrderCountVo> orderCountVoList
            = baseMapper.selectOrderCount(orderCountQueryVo);
    //日期列表
    List<String> dateList
            =orderCountVoList.stream().map(OrderCountVo::getReserveDate).collect(Collectors.toList());
    //统计列表
    List<Integer> countList
            =orderCountVoList.stream().map(OrderCountVo::getCount).collect(Collectors.toList());
    map.put("dateList", dateList);
    map.put("countList", countList);
    return map;
  }

  private OrderInfo packageOrder(OrderInfo orderInfo) {
    orderInfo.getParam().put("orderStatusString", OrderStatusEnum.getStatusNameByStatus(orderInfo.getOrderStatus()));
    return orderInfo;
  }
}
